package com.ljj.examisto.receiver

import android.Manifest
import android.app.Notification
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.media.Ringtone
import android.media.RingtoneManager
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import com.ljj.examisto.R
import com.ljj.examisto.ui.activity.EditExamActivity
import com.ljj.examisto.util.Logger.TAG
import com.ljj.examisto.util.NotificationChannelInfo
import com.ljj.examisto.util.RemindOptionProvider

class ReminderBroadcastReceiver : BroadcastReceiver() {
    companion object {
        private var currentRingtone: Ringtone? = null
        private const val DISMISS_REQUEST_CODE_OFFSET = 1000
        private const val DELETE_REQUEST_CODE_OFFSET = 999
    }
    private lateinit var prefs: SharedPreferences

    override fun onReceive(context: Context, intent: Intent) {
        initProperties(context)
        when (intent.action) {
            "com.ljj.examisto.ACTION_DISMISS_ALARM" -> {
                Log.d(TAG, "收到关闭闹钟广播")
                val requestCode = intent.getIntExtra("requestCode", 0)
                dismissAlarm(context, requestCode)
            }
            "com.ljj.examisto.ACTION_REMIND" -> {
                Log.d(TAG, "收到提醒广播")
                handleRemindAction(context, intent)
            }
            else -> {
                Log.e(TAG, "未知的广播动作: ${intent.action}")
            }
        }
    }

    private fun initProperties(context: Context) {
        prefs = context.getSharedPreferences(context.getString(R.string.app_preference_name), Context.MODE_PRIVATE)
    }

    private fun handleRemindAction(context: Context, intent: Intent) {
        // 获取广播携带的数据
        val examName = intent.getStringExtra("examName") ?: "未知考试"
        val seconds = intent.getIntExtra("seconds", 0)
        val type = intent.getStringExtra("type") ?: "UNKNOWN"
        val requestCode = intent.getIntExtra("requestCode", 0)
        when (type) {
            "NOTIFICATION" -> showNotification(context, examName, seconds, requestCode)
            "ALARM" -> showAlarm(context, examName, seconds, requestCode)
            else -> Log.e(TAG, "未知的提醒类型：$type")
        }
    }

    private fun showNotification(context: Context, examName: String, seconds: Int, requestCode: Int) {
        Log.d(TAG, "显示提醒通知")
        val restTimeString = RemindOptionProvider.findNameByValue(seconds)
        // 用于跳转到 EditExamActivity
        val intent = Intent(context, EditExamActivity::class.java).apply {
            putExtra("EXAM_NAME", examName) // 传递考试名称作为参数
        }
        val pendingIntent = PendingIntent.getActivity(
            context,
            requestCode,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )
        val notification = NotificationCompat.Builder(context, NotificationChannelInfo.REMIND_CHANNEL_ID)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("考前通知")
            .setContentText("$examName 考试将在 $restTimeString 后开始！")
            .setContentIntent(pendingIntent)
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setAutoCancel(true)
            .setDefaults(Notification.DEFAULT_VIBRATE)
            .build()
        showNotificationWithPermissionCheck(context, notification, requestCode)
    }

    private fun showAlarm(context: Context, examName: String, seconds: Int, requestCode: Int) {
        Log.d(TAG, "显示提醒闹钟")
        val restTimeString = RemindOptionProvider.findNameByValue(seconds)
        val shutdownTime = prefs.getInt(context.getString(R.string.key_automatically_shutdown_time), 300)
        // 创建用于跳转到 EditExamActivity 的Intent
        val intent = Intent(context, EditExamActivity::class.java).apply {
            putExtra("EXAM_NAME", examName) // 传递考试名称作为参数
        }
        val pendingIntent = PendingIntent.getActivity(
            context,
            requestCode,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )
        // 创建关闭按钮的Intent
        val dismissIntent = Intent(context, ReminderBroadcastReceiver::class.java).apply {
            action = "com.ljj.examisto.ACTION_DISMISS_ALARM"
            putExtra("requestCode", requestCode)
        }
        val dismissPendingIntent = PendingIntent.getBroadcast(
            context,
            requestCode + DISMISS_REQUEST_CODE_OFFSET,
            dismissIntent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )
        // 创建用于监听通知被清除的Intent
        val deleteIntent = Intent(context, ReminderBroadcastReceiver::class.java).apply {
            action = "com.ljj.examisto.ACTION_DISMISS_ALARM"
            putExtra("requestCode", requestCode)
        }
        val deletePendingIntent = PendingIntent.getBroadcast(
            context,
            requestCode + DELETE_REQUEST_CODE_OFFSET,
            deleteIntent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )
        // 创建通知
        val notification = NotificationCompat.Builder(context, NotificationChannelInfo.REMIND_CHANNEL_ID)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("考前闹钟（${shutdownTime}秒后自动关闭）")
            .setContentText("$examName 考试将在 $restTimeString 后开始！")
            .setContentIntent(pendingIntent)
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setAutoCancel(true)
            .setDefaults(Notification.DEFAULT_VIBRATE)
            .addAction(R.drawable.ic_cancel, "关闭", dismissPendingIntent)
            .setDeleteIntent(deletePendingIntent)
            .build()
        showNotificationWithPermissionCheck(context, notification, requestCode)
        // 延迟关闭闹铃和通知
        Handler(Looper.getMainLooper()).postDelayed({
            currentRingtone?.stop()
            currentRingtone = null
            NotificationManagerCompat.from(context).cancel(requestCode)
        }, (shutdownTime * 1000).toLong())
        // 播放闹铃（先停止之前的铃声）
        currentRingtone?.stop()
        val ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM)
            ?: RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
        currentRingtone = RingtoneManager.getRingtone(context, ringtoneUri)
        currentRingtone?.play()
    }

    private fun showNotificationWithPermissionCheck(
        context: Context,
        notification: Notification,
        requestCode: Int
    ) {
        val notificationManager = NotificationManagerCompat.from(context)
        if (ActivityCompat.checkSelfPermission(
                context,
                Manifest.permission.POST_NOTIFICATIONS
            ) == PackageManager.PERMISSION_GRANTED
        ) {
            notificationManager.notify(requestCode, notification)
        } else {
            Log.w(TAG, "没有通知权限，无法显示通知")
        }
    }

    private fun dismissAlarm(context: Context, requestCode: Int) {
        Log.d(TAG, "关闭提醒闹钟，requestCode=$requestCode")
        // 取消通知
        NotificationManagerCompat.from(context).cancel(requestCode)
        // 停止闹钟铃声
        currentRingtone?.stop()
        currentRingtone = null
    }
}